//
// License
// Released under the New BSD License
// Author: Alex Wilkinson
//

// Constants for convience
if (typeof(Cc) == "undefined")
  var Cc = Components.classes;
if (typeof(Ci) == "undefined")
  var Ci = Components.interfaces;
if (typeof(Cu) == "undefined")
  var Cu = Components.utils;
if (typeof(Cr) == "undefined")
  var Cr = Components.results;
	
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://telescope/modules/io.js"); 
Cu.import("resource://telescope/modules/Preferences.js"); 
		
var TelescopeWindow = {
	_SPS: null,
	_TStrings: null,
	_TNS: "http://awilco.net/telescope#",
	_RemotesNode: null,
	_daapService: null,
	console: null,
	onLoad: function()
	{
		this.console = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService);
		this._SPS = Cc['@songbirdnest.com/servicepane/service;1'].
					getService(Ci.sbIServicePaneService);
		
		this._TStrings = document.getElementById("telescope-strings"); 
		
		this.removeStaleNodes();
		
		try
		{
			this._daapService = Components.classes["@awilco.net/daapd;1"]
                                 .getService(Components.interfaces.awIHttpRequestHandler).wrappedJSObject;
								 
			//Start Browsing
			this._RemotesNode = this.getRemotesNode();
			this._daapService.browseForRemotes(this);
		}catch(e) { dump(e); }
		
		//do first run check
		this.checkFirstRun();
    },
	onUnLoad: function()
	{
		this.removeStaleNodes();
	},
	getRemotesNode: function()
	{
		var remotesNode = this._SPS.getNode("AW:Remotes");
		
		if (remotesNode)
			remotesNode.hidden = false;
		else
		{
			remotesNode = this._SPS.createNode();
			remotesNode.id = "AW:Remotes";
			remotesNode.className = 'folder remotes';
			remotesNode.name = 'Remotes';
			remotesNode.editable = false;
			remotesNode.setAttributeNS('http://songbirdnest.com/rdf/servicepane#', 'Weight', 1);
			remotesNode.setAttributeNS('http://songbirdnest.com/rdf/servicepane#', "addonID", "telescope@awilco.net");
			remotesNode.setAttributeNS(this._TNS, "remotesFolder", true);
			remotesNode.hidden = false;
			this._SPS.root.appendChild(remotesNode);
		}
		return remotesNode;
	},
	onRemoteFound: function(remoteID,remoteName)
	{
		var nodeID = this.createShortID(remoteID);	
		//Check in case it already exists
		if (this._SPS.getNode('rm:' + nodeID)) return;
		
		var node = this._SPS.createNode();
		node.id = 'rm:' + nodeID;
		node.name = remoteName;
		node.image = 'chrome://telescope/content/remote.png';
		node.url = this.createXULFile(remoteID);
		node.setAttributeNS(this._TNS, "isRemote", true);
		node.setAttributeNS('http://songbirdnest.com/rdf/servicepane#', "addonID", "telescope@awilco.net");
		node.hidden = false;
		node.editable = false;
		this._RemotesNode.appendChild(node);
		this._RemotesNode.hidden = false;
	},
	onRemotePaired: function(remoteID)
	{
		var nodeID = this.createShortID(remoteID.toString());
		var node = this._SPS.getNode('rm:' + nodeID);
		if (node != null)
		{
			node.image = 'chrome://telescope/content/remote_paired.png';
		}
	},
	onRemoteLost: function(remoteID)
	{
		var nodeID = this.createShortID(remoteID.toString());	
		var node = this._SPS.getNode('rm:' + nodeID);
		if (node != null)
			this._SPS.removeNode(node);
	},
	createShortID: function(remoteID)
	{	//creates a hex code from the last 5 characters of remote ID
		//use hex in order to make sure no illegal characters in Node id name
		var shortID = remoteID;
		if (shortID.length > 5)	shortID = shortID.substr(shortID.length-5,5);
		//convert to hex
		var newID = '';
		for (i=0;i<shortID.length;i++)
		{
			var val = shortID.charCodeAt(i);
			
			var num = (val >> 4);
			num = num + (( num > 9) ? 55 : 48);
			var first = String.fromCharCode(num);
			
			num = (val % 16);
			num = num + (( num > 9) ? 55 : 48);
			var second = String.fromCharCode(num);
			
			newID += first + second;
		}
		return newID;
	},
	createXULFile: function(remoteID)
	{	//creates a unique XUL file for this remote containing the remote ID, which then opens a proper window
		//a massive HACK as I can't see how to transfer information when a service pane node is clicked
		var MY_ID = "telescope@awilco.net";  
	var em = Components.classes["@mozilla.org/extensions/manager;1"].getService(Components.interfaces.nsIExtensionManager);  
		var file = em.getInstallLocation(MY_ID).getItemFile(MY_ID, "install.rdf");  
		
		file = file.parent;
		file.append('chrome');
		file.append('content');
		file.append('remote_' + remoteID + '.xul');
		FileIO.write(file,'<?xml version="1.0"?>\n<page id="redirect-window" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="redirect(\'' + remoteID + '\')">\n<script type="application/x-javascript" src="chrome://telescope/content/redirect.js" />\n</page>');
		return 'chrome://telescope/content/' + 'remote_' + remoteID + '.xul';
	},
	findFolderNode: function(aNode) 
	{
    if (!aNode) {
      aNode = this._SPS.root;
    }
    /* check if this is our node */
    let found = aNode.hasAttributeNS(this._TNS, "remotesFolder");
    if(found) {
      return aNode;
    }

    /* search between our children */
    let children = aNode.childNodes;
    while (children.hasMoreElements()) {
      let child = children.getNext().QueryInterface(Ci.sbIServicePaneNode);
      let result = this.findFolderNode(child);
      if (result != null) {
        return result;
      }
    }
  
    /* not found! */
    return null;
  },  //findFolderNode
  removeStaleNodes: function(aNode) 
  {
		if (!aNode) {
		  aNode = this._SPS.root;
		}
		
		if(aNode.hasAttributeNS(this._TNS, "isRemote") || aNode.hasAttributeNS(this._TNS, "remotesFolder") || aNode.name == 'Remotes') {
			this._SPS.removeNode(aNode);
		}
		
		let children = aNode.childNodes;
		while (children.hasMoreElements()) {
		  let child = children.getNext().QueryInterface(Ci.sbIServicePaneNode);
		  this.removeStaleNodes(child);
		}
	  
		/* not found! */
		return null;
	},
	checkFirstRun: function()
	{
		var version = Cc["@mozilla.org/extensions/manager;1"]
                .getService(Ci.nsIExtensionManager)
                .getItemForID('telescope@awilco.net')
                .version;		
		var storedVersion = Preferences.get("extensions.telescope.version",'0');
		
		if (version != storedVersion)
		{
			var mediator = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
			mediator.getMostRecentWindow('Songbird:Main').openUILinkIn("chrome://telescope/content/welcome.html", "tab");
			Preferences.set("extensions.telescope.version",version);
		}
	},
	QueryInterface: XPCOMUtils.generateQI([Ci.awIDnssdRemoteListener, Ci.nsISupportsWeakReference]),
}

window.addEventListener("load", function(e) { TelescopeWindow.onLoad(e); }, false);
window.addEventListener("unload", function(e) { TelescopeWindow.onUnLoad(e); }, false);
